import axios from "axios";
import { ElNotification } from "element-plus";
import { BASE_API, BASE_API_TIMEOUT, YOU_CANNOT_USE_CODE } from "@/setting";
import { useUserStore } from "@/stores/user";

// 创建axios实例
const service = axios.create({
  baseURL: BASE_API, // api 的 base_url
  timeout: BASE_API_TIMEOUT, // 请求超时时间
  withCredentials: true,
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers["auth"] = userStore.token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    // 拦截 没有权限的访问
    let code = response.data?.code ?? 0;
    if (YOU_CANNOT_USE_CODE.includes(code)) {
      ElNotification({
        title: "Error",
        message: response.data.message,
        type: "error",
      });
      return Promise.reject(response.data.message);
    }
    return response.data;
  },
  (error) => {
    let code = 0;
    try {
      code = error.response.data.status;
    } catch (e) {
      if (error.toString().indexOf("Error: timeout") !== -1) {
        ElNotification({
          title: "Error",
          message: "网络请求超时",
          type: "error",
        });
        return Promise.reject(error);
      }
    }
    console.log("req err code == > ", code);
    // if (code) {
    //   // TODO
    // } else {
    ElNotification({
      title: "Error",
      message: "接口请求失败",
      type: "error",
    });
    // }
    return Promise.reject(error);
  }
);
export default service;
